package com.caul.demo.hadoop.mapreduce.join;

import org.apache.commons.lang.StringUtils;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.lib.input.FileSplit;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by sdliang on 2018/4/9.
 */
public class JoinCacheMapper extends Mapper<LongWritable, Text, Text, JoinBean> {

    private Map<String, JoinBean> profileMap;

    @Override
    protected void setup(Context context) throws IOException, InterruptedException {
        cacheProfiles(context.getConfiguration().get("file.cache"));
    }

    @Override
    protected void map(LongWritable key, Text value, Context context)
            throws IOException, InterruptedException {
        String[] split = value.toString().split(":");
        JoinBean bean = profileMap.get(split[1]).clone();
        bean.setOrderid(split[0]);
        context.write(new Text(bean.getUid()), bean);
    }

    private void cacheProfiles(String profile) throws IOException {
        profileMap = new HashMap<>();
        File file = new File(URI.create(profile));
        BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
        try {
            String line;
            JoinBean bean;
            while (StringUtils.isNotBlank(line = bufferedReader.readLine())) {
                bean = new JoinBean();
                String[] split = line.split(":");
                String[] split2 = split[1].split(",");
                bean.set(split[0], split2[0], split2[1], split2[2], JoinBean.FILE_PROFILE);
                profileMap.put(bean.getUid(), bean);
            }
        } finally {
            bufferedReader.close();
        }
    }
}
